package com.dynamicthreadpool.netty.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/**
 * 线程池消息编码器
 */
public class ThreadPoolMessageEncoder extends MessageToByteEncoder<ThreadPoolControlMessage> {
    
    @Override
    protected void encode(ChannelHandlerContext ctx, ThreadPoolControlMessage msg, ByteBuf out) throws Exception {
        // 使用Java序列化将对象转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(msg);
        oos.flush();
        byte[] bytes = baos.toByteArray();
        
        // 先写入消息长度，再写入消息内容
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
        
        oos.close();
        baos.close();
    }
}